// scramble-game.js - 拼词游戏逻辑
const { playRightSound, playWrongSound, playClickSound } = require('../../../../utils/audioUtils.js');
const storageManager = require('../../../../manager/storageManager').getInstance();
const audioManager = require('../../../../manager/audioManager').getInstance();

Page({
  data: {
    score: 0,
    currentRound: 1,
    totalRounds: 8,
    currentWord: null,
    letterTiles: [],
    answerSlots: [],
    hintsLeft: 3,
    correctAnswers: 0,
    wrongAnswers: 0,
    gameOver: false,
    resultIcon: '',
    resultTitle: '',
    stars: 0,
    accuracy: 0,
    showToast: false,
    toastMessage: '',
    toastIcon: '',
    toastBg: '#4caf50',
    wordsList: [],
    isProcessingAnswer: false // 添加状态标志，防止在处理答案期间重复点击
  },

  onLoad: function() {
    const app = getApp();
    this.wordDataManager = app.globalData.wordDataManager;
    this.magicCoinManager = app.getMagicCoinManager();
    // 异步调用initGame并处理可能的错误
    this.initGame().catch(error => {
      console.error('游戏初始化失败:', error);
    });
  },

  // 初始化游戏
  async initGame() {
    try {
      wx.showLoading({ title: '加载单词中...', mask: true });
      
      // 获取随机单词
      let words = this.getRandomWords(8);
      
      // 检查是否需要丰富单词数据
      const needsEnrichment = words.some(word => !this.wordDataManager._isWordEnriched(word));
      
      if (needsEnrichment) {
        // 丰富单词数据
        await this.wordDataManager.enrichWords(words.map(word => word.id));
        // 重新获取已丰富的单词
        const wordIds = words.map(word => word.id);
        words = wordIds.map(id => this.wordDataManager.getWordById(id)).filter(Boolean);
      }
      
      this.setData({
        wordsList: words,
        score: 0,
        currentRound: 1,
        correctAnswers: 0,
        wrongAnswers: 0,
        hintsLeft: 3,
        gameOver: false
      });
      
      this.loadNextWord();
    } catch (error) {
      console.error('游戏初始化失败:', error);
      this.showToast('❌', '加载失败，请重试', '#f44336');
    } finally {
      wx.hideLoading();
    }
  },

  // 获取随机单词
  getRandomWords: function(count) {
    const wordsDict = this.wordDataManager.getAllWords();
    // 将对象转换为数组
    const allWords = Object.values(wordsDict).filter(word => word && word.english && word.chinese);
    // 过滤出长度适中的单词（3-8个字母）
    const suitableWords = allWords.filter(w => w.english.length >= 3 && w.english.length <= 8);
    if (suitableWords.length === 0) {
      console.error('没有合适的单词');
      return [];
    }
    const shuffled = this.shuffleArray(suitableWords);
    return shuffled.slice(0, Math.min(count, suitableWords.length));
  },

  // 加载下一个单词
  loadNextWord: function() {
    if (this.data.currentRound > this.data.totalRounds) {
      this.endGame();
      return;
    }

    const word = this.data.wordsList[this.data.currentRound - 1];
    const letters = word.english.toUpperCase().split('');
    const scrambledLetters = this.shuffleArray([...letters]);

    const letterTiles = scrambledLetters.map((letter, index) => ({
      letter,
      used: false,
      animation: null
    }));

    const answerSlots = new Array(letters.length).fill(null);

    this.setData({
      currentWord: word,
      letterTiles,
      answerSlots
    });
  },

  // 打乱数组
  shuffleArray: function(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 选择字母
  selectLetter: function(e) {
    // 播放点击音效
    playClickSound();
    
    const index = e.currentTarget.dataset.index;
    const tile = this.data.letterTiles[index];

    if (tile.used) return;

    // 找到第一个空槽位
    const emptySlotIndex = this.data.answerSlots.findIndex(slot => slot === null);
    if (emptySlotIndex === -1) return;

    // 更新字母状态
    const letterTiles = [...this.data.letterTiles];
    letterTiles[index].used = true;

    // 更新答案槽位
    const answerSlots = [...this.data.answerSlots];
    answerSlots[emptySlotIndex] = tile.letter;

    this.setData({ letterTiles, answerSlots });
  },

  // 从答案中移除字母
  removeFromAnswer: function(e) {
    // 播放点击音效
    playClickSound();
    
    const slotIndex = e.currentTarget.dataset.index;
    const letter = this.data.answerSlots[slotIndex];

    if (!letter) return;

    // 找到对应的字母块并恢复
    const letterTiles = [...this.data.letterTiles];
    const tileIndex = letterTiles.findIndex(tile => tile.letter === letter && tile.used);
    if (tileIndex !== -1) {
      letterTiles[tileIndex].used = false;
    }

    // 清空槽位
    const answerSlots = [...this.data.answerSlots];
    answerSlots[slotIndex] = null;

    this.setData({ letterTiles, answerSlots });
  },

  // 清空答案
  clearAnswer: function() {
    // 播放点击音效
    playClickSound();
    const letterTiles = this.data.letterTiles.map(tile => ({
      ...tile,
      used: false
    }));

    const answerSlots = new Array(this.data.answerSlots.length).fill(null);

    this.setData({ letterTiles, answerSlots });
  },

  // 使用提示
  useHint: function() {
    // 播放点击音效
    playClickSound();
    
    if (this.data.hintsLeft <= 0) return;

    const correctWord = this.data.currentWord.english.toUpperCase();
    const currentAnswer = this.data.answerSlots.join('');

    // 找到第一个错误或空的位置
    let hintIndex = -1;
    for (let i = 0; i < correctWord.length; i++) {
      if (this.data.answerSlots[i] !== correctWord[i]) {
        hintIndex = i;
        break;
      }
    }

    if (hintIndex === -1) return;

    // 如果该位置已有字母，先移除
    if (this.data.answerSlots[hintIndex]) {
      const letter = this.data.answerSlots[hintIndex];
      const letterTiles = [...this.data.letterTiles];
      const tileIndex = letterTiles.findIndex(tile => tile.letter === letter && tile.used);
      if (tileIndex !== -1) {
        letterTiles[tileIndex].used = false;
      }
      this.setData({ letterTiles });
    }

    // 放置正确的字母
    const correctLetter = correctWord[hintIndex];
    const letterTiles = [...this.data.letterTiles];
    const tileIndex = letterTiles.findIndex(tile => tile.letter === correctLetter && !tile.used);
    
    if (tileIndex !== -1) {
      letterTiles[tileIndex].used = true;
      const answerSlots = [...this.data.answerSlots];
      answerSlots[hintIndex] = correctLetter;

      this.setData({
        letterTiles,
        answerSlots,
        hintsLeft: this.data.hintsLeft - 1
      });

      this.showToast('💡', '提示已使用', '#ff9800');
    }
  },

  // 检查答案
  checkAnswer: function() {
    // 如果正在处理答案或游戏已结束，则直接返回
    if (this.data.isProcessingAnswer || this.data.gameOver) {
      return;
    }
    
    // 设置正在处理答案标志
    this.setData({ isProcessingAnswer: true });
    
    // 播放点击音效
    playClickSound();
    const userAnswer = this.data.answerSlots.join('');
    const correctAnswer = this.data.currentWord.english.toUpperCase();

    if (userAnswer.includes(null) || userAnswer.length !== correctAnswer.length) {
      this.showToast('⚠️', '请完成拼写', '#ff9800');
      // 重置处理状态
      this.setData({ isProcessingAnswer: false });
      return;
    }

    if (userAnswer === correctAnswer) {
      this.handleCorrectAnswer();
    } else {
      this.handleWrongAnswer();
    }
  },

  // 处理正确答案
  handleCorrectAnswer: function() {
    const score = this.data.score + 100;
    const correctAnswers = this.data.correctAnswers + 1;

    this.setData({ score, correctAnswers });

    this.showToast('🎉', '太棒了！答对了！', '#4caf50');

    // 播放正确音效
    playRightSound();
    wx.vibrateShort({ type: 'medium' });
    
    // 播放当前单词的音频
    if (this.data.currentWord && this.data.currentWord.english) {
      const wordObj = {
        id: this.data.currentWord.id,
        english: this.data.currentWord.english,
        pronunciation: this.data.currentWord.pronunciation
      };
      // 使用audioManager播放单词发音
      audioManager.playPronunciation(wordObj, 1.0, 'american').catch(error => {
        console.error('播放单词发音失败:', error);
      });
    }

    setTimeout(() => {
      const currentRound = this.data.currentRound + 1;
      this.setData({ 
        currentRound,
        isProcessingAnswer: false // 重置处理状态
      });
      this.loadNextWord();
    }, 1500);
  },

  // 处理错误答案
  handleWrongAnswer: function() {
    const score = Math.max(0, this.data.score - 20);
    const wrongAnswers = this.data.wrongAnswers + 1;

    this.setData({ score, wrongAnswers });

    this.showToast('❌', '答错了，再试一次！', '#f44336');

    playWrongSound();
    wx.vibrateShort({ type: 'heavy' });

    // 清空答案
    setTimeout(() => {
      this.clearAnswer();
      this.setData({ isProcessingAnswer: false }); // 重置处理状态
    }, 1000);
  },

  // 显示提示信息
  showToast: function(icon, message, bg) {
    this.setData({
      showToast: true,
      toastIcon: icon,
      toastMessage: message,
      toastBg: bg
    });

    setTimeout(() => {
      this.setData({ showToast: false });
    }, 1500);
  },

  // 结束游戏
  endGame: function() {
    const totalAttempts = this.data.correctAnswers + this.data.wrongAnswers;
    const accuracy = totalAttempts > 0 ? Math.round((this.data.correctAnswers / totalAttempts) * 100) : 0;
    let stars = 0;
    let resultIcon = '';
    let resultTitle = '';

    if (accuracy >= 90) {
      stars = 3;
      resultIcon = '🏆';
      resultTitle = '完美表现！';
    } else if (accuracy >= 70) {
      stars = 2;
      resultIcon = '🌟';
      resultTitle = '表现不错！';
    } else {
      stars = 1;
      resultIcon = '👍';
      resultTitle = '继续加油！';
    }

    // 奖励魔法币
    const coins = stars * 10;
    this.magicCoinManager.addMagicCoins(coins, `拼词游戏 - ${stars}星`);

    // 保存游戏记录
    this.saveGameRecord(stars);

    this.setData({
      gameOver: true,
      accuracy,
      stars,
      resultIcon,
      resultTitle
    });
  },

  // 保存游戏记录
  saveGameRecord: function(stars) {
    try {
      const gameStats = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS) || {
        totalGamesPlayed: 0,
        totalStars: 0,
        highScore: 0,
        matching: { played: 0, bestScore: 0 },
        scramble: { played: 0, bestScore: 0 },
        memory: { played: 0, bestScore: 0 }
      };

      gameStats.totalGamesPlayed += 1;
      gameStats.totalStars += stars;
      gameStats.highScore = Math.max(gameStats.highScore, this.data.score);
      gameStats.scramble.played += 1;
      gameStats.scramble.bestScore = Math.max(gameStats.scramble.bestScore, this.data.score);

      storageManager.setStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS, gameStats);

      const recentGames = storageManager.getStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES) || [];
      recentGames.unshift({
        id: Date.now(),
        gameName: '拼词游戏',
        icon: '🔤',
        score: this.data.score,
        stars,
        timestamp: new Date().toISOString()
      });

      storageManager.setStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES, recentGames.slice(0, 10));
    } catch (error) {
      console.error('保存游戏记录失败:', error);
    }
  },

  // 重新开始游戏
  async restartGame() {
    // 播放点击音效
    playClickSound();
    await this.initGame();
  },

  // 返回
  goBack: function() {
    // 播放点击音效
    playClickSound();
    wx.navigateBack();
  },
  
  // 转发给朋友
  onShareAppMessage: function() {
    return {
      title: `我在拼词游戏中答对了${this.data.correctAnswers}个单词！快来挑战吧！`,
      path: '/pages/challenge/word-games/scramble-game/scramble-game',
      // imageUrl: '/images/challenge.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: `我在拼词游戏中答对了${this.data.correctAnswers}个单词！快来挑战吧！`,
      query: 'from=timeline',
      // imageUrl: '/images/challenge.png'
    };
  }
});
